package com.ftf.tp.user.infrastructure.repository;


import com.alibaba.fastjson.JSONObject;
import com.ftf.tp.common.constants.RedisConstant;
import com.ftf.tp.common.core.exception.BusinessException;
import com.ftf.tp.common.core.redis.utils.RedissonHelper;
import com.ftf.tp.common.core.utils.SnowIdUtils;
import com.ftf.tp.common.security.constants.UserVO;
import com.ftf.tp.user.application.adapter.http.PassportRestAdaptor;
import com.ftf.tp.user.application.vo.PassportUserVO;
import com.ftf.tp.user.domain.data.dos.TpUserDO;
import com.ftf.tp.user.domain.data.repository.UserRepository;
import com.ftf.tp.user.infrastructure.converter.TpUserConverter;
import com.ftf.tp.user.infrastructure.mapper.TpUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户仓储
 *
 * @author tanghao
 * @date 2021/11/11
 */
@Slf4j
@Service
public class UserRepositoryImpl implements UserRepository {

    /**
     * 用户数据库操作类
     */
    @Resource
    private TpUserMapper tpUserMapper;

    /**
     * redisson操作类
     */
    @Resource
    private RedissonHelper redissonHelper;

    @Resource
    private PassportRestAdaptor passportAdaptor;


    @Override
    public TpUserDO getByPassportId(Long passportId) {
        return TpUserConverter.INSTANCE.convert(tpUserMapper.getByPassportId(passportId));
    }

    /**
     * 获取tp网站用户信息 根据passportId
     *
     * @return 当前登陆用户信息
     */
    public TpUserDO getTpUser(Long passportId) {
        TpUserDO tpUserDO;
        Object userInfoByCache = redissonHelper.getValue(RedisConstant.TP_USER_INFO + passportId);
        if (ObjectUtils.isEmpty(userInfoByCache)) {
            //缓存中没有,去数据库中获取
            tpUserDO = getTpUserInit(passportId);
            //将数据库里的数据存入缓存
            redissonHelper.setValue(RedisConstant.TP_USER_INFO + passportId, tpUserDO);
        } else {
            tpUserDO = (TpUserDO) userInfoByCache;
        }
        return tpUserDO;
    }

    /**
     * 根据passportId获取tp网站用户信息 不存在则初始化一个
     *
     * @param passportId passport用户id
     * @return 当前登陆用户信息
     */
    public TpUserDO getTpUserInit(Long passportId) {
        TpUserDO userDO = getByPassportId(passportId);
        //如果passportId在本地没有找到，就自动创建
        if (ObjectUtils.isEmpty(userDO)) {
            //根据passportId去passPort获取用户信息
            JSONObject object = passportAdaptor.getTpUserInfoByUserId(passportId);
            PassportUserVO passportUserVO = JSONObject.toJavaObject(object, PassportUserVO.class);
            log.info("用户第一次在tp网站登录,从passport获取用户信息:{}", passportUserVO);
            userDO = TpUserDO.builder()
                    .avatar(passportUserVO.getAvatar())
                    .passportId(passportId)
                    .isMember(false)
                    .changeNameNumber(0)
                    .sex(Integer.parseInt(passportUserVO.getSsex()))
                    .fansAmount(0)
                    .authorHotAmount(0L)
                    .level(1)
                    //登录一次加5点经验
                    .levelExperience(5)
                    .userType(0)
                    .userStatus(1)
                    .build();
            if (ObjectUtils.isNotEmpty(passportUserVO.getEmail())) {
                userDO.setEmail(passportUserVO.getEmail());
            }
            if (ObjectUtils.isNotEmpty(passportUserVO.getMobile())) {
                userDO.setPhone(passportUserVO.getMobile());
            }
            if (ObjectUtils.isNotEmpty(passportUserVO.getCreateTime())) {
                userDO.setCreatedTime(passportUserVO.getCreateTime());
            }
            if (ObjectUtils.isNotEmpty(passportUserVO.getModifyTime())) {
                userDO.setUpdatedTime(passportUserVO.getModifyTime());
            }
            if (ObjectUtils.isNotEmpty(passportUserVO.getNickName())) {
                userDO.setNickname(passportUserVO.getNickName());
            } else {
                //当passport没有保存用户昵称时,系统自动生成一个
                userDO.setNickname("用户_" + SnowIdUtils.uniqueLong());
            }
            insert(userDO);
        }
        return userDO;
    }

    @Override
    public TpUserDO getUserInfo() {
        UserVO userVO;
        try {
            //获取passport用户信息
            userVO = (UserVO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (Exception e) {
            log.error("当前用户未登录", e);
            throw new BusinessException("当前用户未登录");
        }
        //将passport用户信息置换为tp网站用户信息
        return getTpUser(userVO.getUserId());
    }

    @Override
    public void insert(TpUserDO userDO) {
        tpUserMapper.insert(TpUserConverter.INSTANCE.convert(userDO));
    }

    @Override
    public TpUserDO byId(Long authorId) {
        return TpUserConverter.INSTANCE.convert(tpUserMapper.selectById(authorId));
    }

    @Override
    public List<Long> selectFollowerList(Long articleAuthorId) {
        return null;
    }

    @Override
    public void update(TpUserDO tpUserDO) {
        tpUserMapper.updateById(TpUserConverter.INSTANCE.convert(tpUserDO));
    }
}
